﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace XYZshell.Game.CardGameEngine
{
	/// <summary>
	/// 基本条件表达式
	/// </summary>
	[Expression( "base" )]
	public abstract class BaseExpression :GameObject, ICondition,IXMLable
	{
		/// <summary>
		/// 构造函数
		/// </summary>
		public BaseExpression()
		{
			Params = new ExpressionParamCollection();
		}
		/// <summary>
		/// 参数集合
		/// </summary>
		public ExpressionParamCollection Params
		{
			get;
			set;
		}

		//BaseExpression Expression
		//{
		//    get;
		//    set;
		//}
		/// <summary>
		/// 活动当前表达的表达式特性
		/// </summary>
		/// <returns></returns>
		protected  ExpressionAttribute GetAttribute()
		{

		
			object[] attrs= this.GetType().GetCustomAttributes( typeof( ExpressionAttribute ), false );
			if (attrs.Length > 0)
				return attrs[0] as ExpressionAttribute;
			return null;
		}


		/// <summary>
		/// 从XML中生成基本条件表达式
		/// </summary>
		/// <param name="xmlnode">XML内容</param>
		/// <returns>基本条件表达式</returns>
		public static  BaseExpression FromXML( string xmlnode )
		{
			XObject xo=new XObject( xmlnode );
			Type exprAttr=ExpressionHelper.GetExpressionByID( xo.Type );
			return   (BaseExpression)exprAttr.InvokeMember( "FromXML", System.Reflection.BindingFlags.InvokeMethod, null, null, new object[] { xmlnode } );
		
		}

		/// <summary>
		/// 转换为XML
		/// </summary>
		/// <returns>转换后的XML</returns>
		public virtual  string ToXML()
		{
			StringBuilder sb=new StringBuilder();
			sb.AppendFormat( "<expression type=\"{0}\">\r\n", this.GetAttribute().ID );
			sb.Append( GetParamsXml() );
			sb.AppendFormat( "</expression>\r\n",GetAttribute().ID );

			return sb.ToString();
		}
		/// <summary>
		/// 获得参数的xml
		/// </summary>
		/// <returns></returns>
		protected string GetParamsXml()
		{
			StringBuilder sb=new StringBuilder();
			if (Params.Count > 0)
			{
				sb.AppendLine( "<params>" );
				foreach (ExpressionParam param in this.Params)
				{
					sb.AppendLine( param.ToXML() );
				}
				sb.AppendLine( "</params>" );
			}
			return sb.ToString();
		}

		#region ICondition 成员


		public event EventHandler  ResultChanged;

		/// <summary>
		/// 返回基本条件表达式结果
		/// </summary>
		/// <returns>条件表达式结果</returns>
		public abstract bool Result();

		#endregion
	}
}
